{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 字符串的应用\n",
    "\n",
    "这里主要以看例子学习为主，查看下面的例子。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s\\np\tam\n"
     ]
    }
   ],
   "source": [
    "#-- 常见字符串常量和表达式\n",
    "S1 = ''                                  # 空字符串 Empty string\n",
    "S2 = \"spam’s\"                            # 双引号和单引号相同\n",
    "S3 = \"s\\\\np\\tam\"                           # 转义字符 Escape characters\n",
    "S4 = \"\"\"spam\"\"\"                          # 三重引号字符串，一般用于函数说明\n",
    "S5 = r'\\temp'                            # Raw字符串，不会进行转义，抑制转义\n",
    "S6 = u'spam'                             # Python2.X中的Unicode字符串\n",
    "print(S3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字符串操作（String operations）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ABCD12345\n",
      "ABCDABCDABCD\n",
      "A 23 4\n"
     ]
    }
   ],
   "source": [
    "# 字符串操作\n",
    "s1 = \"ABCD\"\n",
    "s2 = \"12345\"\n",
    "print(s1+s2)\n",
    "print(s1*3)\n",
    "\n",
    "print(s1[0], s2[1:3], len(s1))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "456\n"
     ]
    }
   ],
   "source": [
    "s2 = \"12345678\"\n",
    "# 456\n",
    "print(s2[3:6])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### EX1：\n",
    "\n",
    "a = Louis card number is 0766310 \n",
    "\n",
    "b = Tom card number is 0981101\n",
    "\n",
    "Can you extract the student card number? Print out the format as follows:\n",
    "\n",
    "Louis:0766310\n",
    "\n",
    "Tom:0981101"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "a = \"Louis card = 0766310\"\n",
    "b = \"Tom card = 0981101\"\n",
    "print (a[0:5] +':'+ a[13:len(a)])\n",
    "# other way? split"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TODO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "----membership relations----\n",
      "A\n",
      "B\n",
      "C\n",
      "D\n"
     ]
    }
   ],
   "source": [
    "# 字符串迭代，成员关系 String iteration, membership relations\n",
    "s1 = \"ABCD\"\n",
    "print('----membership relations----')\n",
    "for x in s1:\n",
    "    print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "----字符串的合并 Merging of strings----\n",
      "a+b+c\n"
     ]
    }
   ],
   "source": [
    "print('----字符串的合并 Merging of strings----')\n",
    "# output resultg：a,b,c\n",
    "print('+'.join(['a', 'b', 'c']))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "----字符串拆分String Split----\n",
      "['12', '415']\n"
     ]
    }
   ],
   "source": [
    "print('----字符串拆分String Split----')\n",
    "s2 = \"1231415\"\n",
    "# 字符串输出,结果：12,45\n",
    "print(s2.split('31'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tom 0981101\n"
     ]
    }
   ],
   "source": [
    "# first use split  key word \n",
    "b = \"Tom card = 0981101\"\n",
    "L = b.split(\" \")\n",
    "print(L[0],L[3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['http:', '', 'www.cnblogs.com', 'fat39', 'p', '7159881.html']\n"
     ]
    }
   ],
   "source": [
    "# 练习：把 http://www.cnblogs.com/fat39/p/7159881.html 变成 http://www.cnblogs.com\\fat39\\p\\7159881.html\n",
    "s = \"http://www.cnblogs.com/fat39/p/7159881.html\"\n",
    "s = s.split('/')\n",
    "print(s)\n",
    "#print???\n",
    "#print???\n",
    "#print(\"\\\\\".join(s))  # 用 \\ 组合字符， 因为\\本身有意义，如\\n是换行，所以要多加一个\\说明我只是一个普通的\\\n",
    "#  Combine characters with \\, because \\ itself has meaning, e.g. \\n is a line break, so add an extra \\ to show that I'm just a normal \\"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 格式化输出(Formatted output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "It is so cute，I like it\n",
      "Louis is taller than Louis \n",
      "right left right\n"
     ]
    }
   ],
   "source": [
    "print('It is so %s，I like it' % \"cute\")                 # 字符串格式化表达式\n",
    "print('{1} is taller than {1} '.format('Yao', 'Louis'))            # 字符串格式化方法，位置区分 position\n",
    "print('{a} {b} {a}'.format(b='left',a='right'))          # 关键词区分 key"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "更详细内容： https://www.cnblogs.com/fat39/p/7159881.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "#-- Python中的字符串格式化实现1--字符串格式化表达式\n",
    "    \"\"\"\n",
    "    基于C语言的'print'模型，并且在大多数的现有的语言中使用。\n",
    "    通用结构：%[(name)][flag][width].[precision]typecode\n",
    "    \"\"\"\n",
    "    \"this is %d %s bird\" % (1, 'dead')                          # 一般的格式化表达式\n",
    "    \"%s---%s---%s\" % (42, 3.14, [1, 2, 3])                      # 字符串输出：'42---3.14---[1, 2, 3]'\n",
    "    \"%d...%6d...%-6d...%06d\" % (1234, 1234, 1234, 1234)         # 对齐方式及填充：\"1234...  1234...1234  ...001234\"\n",
    "    x = 1.23456789\n",
    "    \"%e | %f | %g\" % (x, x, x)                                  # 对齐方式：\"1.234568e+00 | 1.234568 | 1.23457\"\n",
    "    \"%6.2f*%-6.2f*%06.2f*%+6.2f\" % (x, x, x, x)                 # 对齐方式：'  1.23*1.23  *001.23* +1.23'\n",
    "    \"%(name1)d---%(name2)s\" % {\"name1\":23, \"name2\":\"value2\"}    # 基于字典的格式化表达式\n",
    "    \"%(name)s is %(age)d\" % vars()                              # vars()函数调用返回一个字典，包含了所有本函数调用时存在的变量\n",
    "    \n",
    "#-- Python中的字符串格式化实现2--字符串格式化调用方法\n",
    "    # 普通调用\n",
    "    \"{0}, {1} and {2}\".format('spam', 'ham', 'eggs')            # 基于位置的调用\n",
    "    \"{motto} and {pork}\".format(motto = 'spam', pork = 'ham')   # 基于Key的调用\n",
    "    \"{motto} and {0}\".format('ham', motto = 'spam')             # 混合调用\n",
    "    # 添加键 属性 偏移量 (import sys)\n",
    "    \"my {1[spam]} runs {0.platform}\".format(sys, {'spam':'laptop'})                 # 基于位置的键和属性\n",
    "    \"{config[spam]} {sys.platform}\".format(sys = sys, config = {'spam':'laptop'})   # 基于Key的键和属性\n",
    "    \"first = {0[0]}, second = {0[1]}\".format(['A', 'B', 'C'])                       # 基于位置的偏移量\n",
    "    # 具体格式化\n",
    "    \"{0:e}, {1:.3e}, {2:g}\".format(3.14159, 3.14159, 3.14159)   # 输出'3.141590e+00, 3.142e+00, 3.14159'\n",
    "    \"{fieldname:format_spec}\".format(......)\n",
    "    # 说明:\n",
    "    \"\"\"\n",
    "        fieldname是指定参数的一个数字或关键字, 后边可跟可选的\".name\"或\"[index]\"成分引用\n",
    "        format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]\n",
    "        fill        ::=  <any character>              #填充字符\n",
    "        align       ::=  \"<\" | \">\" | \"=\" | \"^\"        #对齐方式\n",
    "        sign        ::=  \"+\" | \"-\" | \" \"              #符号说明\n",
    "        width       ::=  integer                      #字符串宽度\n",
    "        precision   ::=  integer                      #浮点数精度\n",
    "        type        ::=  \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\" | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\n",
    "    \"\"\"\n",
    "    # 例子:\n",
    "        '={0:10} = {1:10}'.format('spam', 123.456)    # 输出'=spam       =    123.456'\n",
    "        '={0:>10}='.format('test')                    # 输出'=      test='\n",
    "        '={0:<10}='.format('test')                    # 输出'=test      ='\n",
    "        '={0:^10}='.format('test')                    # 输出'=   test   ='\n",
    "        '{0:X}, {1:o}, {2:b}'.format(255, 255, 255)   # 输出'FF, 377, 11111111'\n",
    "        'My name is {0:{1}}.'.format('Fred', 8)       # 输出'My name is Fred    .'  动态指定参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"%d...%6d...%-6d...%06d\" % (1234, 1234, 1234, 1234)      "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 练习3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "apple,banana and grapes are very tasty\n"
     ]
    }
   ],
   "source": [
    "print(\"{0},{1} and {2} are very tasty\".format('apple', 'banana', 'grapes') ) # 打印：apple,banana and grapes are very tasty！\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "apple ,banana and grapes are very tasty\n"
     ]
    }
   ],
   "source": [
    "print(\"{a} ,{b} and {c} are very tasty\".format(a='apple',b='banana', c='grapes')) # 打印：apple,banana and grapes are very tasty！\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 内置字符串处理函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#-- 内置str处理函数：\n",
    "    str1 = \"stringobject\"\n",
    "    # All upper case, all lower case, case conversion, initial capitalization, capitalize the first letter of each word\n",
    "    str1.upper(); str1.lower(); str1.swapcase(); str1.capitalize(); str1.title()        \n",
    "    str1.ljust(width)                       # 获取固定长度，左对齐，右边不够用空格补齐\n",
    "    str1.rjust(width)                       # 获取固定长度，右对齐，左边不够用空格补齐\n",
    "    str1.center(width)                      # 获取固定长度，中间对齐，两边不够用空格补齐\n",
    "    str1.zfill(width)                       # 获取固定长度，右对齐，左边不足用0补齐\n",
    "    str1.find('t',start,end)                # 查找字符串，可以指定起始及结束位置搜索\n",
    "    str1.rfind('t')                         # 从右边开始查找字符串\n",
    "    str1.count('t')                         # 查找字符串出现的次数\n",
    "    #上面所有方法都可用index代替，不同的是使用index查找不到会抛异常，而find返回-1\n",
    "    str1.replace('old','new')               # 替换函数，替换old为new，参数中可以指定maxReplaceTimes，即替换指定次数的old为new\n",
    "    str1.strip();                           # 默认删除空白符\n",
    "    str1.strip('d');                        # 删除str1字符串中开头、结尾处，位于 d 删除序列的字符\n",
    "    str1.lstrip();\n",
    "    str1.lstrip('d');                       # 删除str1字符串中开头处，位于 d 删除序列的字符\n",
    "    str1.rstrip();\n",
    "    str1.rstrip('d')                        # 删除str1字符串中结尾处，位于 d 删除序列的字符\n",
    "    str1.startswith('start')                # 是否以start开头\n",
    "    str1.endswith('end')                    # 是否以end结尾\n",
    "    # 判断字符串是否全为字符、数字、小写、大写\n",
    "    str1.isalnum(); str1.isalpha(); str1.isdigit(); str1.islower(); str1.isupper()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 用Print方式输出查看\n",
    "str1 = \"stringobjects\"\n",
    "print(str1.strip('s'));                        # 删除str1字符串中开头、结尾处的s\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise：\n",
    "\n",
    "一个5位数，判断它是不是回文数。即12321是回文数,个位与万位相同，十位与千位相同\n",
    "> A 5-digit number to determine if it is an iambic number. i.e. 12321 is an iambic number, the digit is the same as the thousands place and the tens place is the same as the thousands place"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input number：213312\n",
      "213312 is right\n"
     ]
    }
   ],
   "source": [
    "# 简单版本\n",
    "x = input('input number：')\n",
    "# is 5 digit number\n",
    "while len(x) != 6:\n",
    "    print(\"error\")\n",
    "    x = input('input number：')\n",
    "\n",
    "# if [0]与[4],[1]与[3] are the sample\n",
    "if x[0]==x[5] and x[1]==x[4] and x[2]==x[3]:\n",
    "    print(\"{0} is right\".format(x))\n",
    "else:\n",
    "    print(\"{0} is error\".format(x))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input number：12333321\n",
      "12333321false\n"
     ]
    }
   ],
   "source": [
    "s = input('input number：')\n",
    "if s[0]==s[4] and s[1]==s[3]:\n",
    "    print( '{0}(true)'.format(s))    \n",
    "else:\n",
    "    print('{0}false'.format(s))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个<strong>6</strong>位数，判断它是不是回文数。即123321是回文数\n",
    "> A 6-digit number to determine if it is an iambic number. i.e. 123321 is the palindrome number"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 根据上题，自己完成，尽量简洁\n",
    "x = input('输入一个6位数')\n",
    "# 可以加一个条件判断是否为六位数\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n digit number, 4,5,6,7,8,9"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
